<template>
  <el-form
    :model="spuInfo"
    :rules="spuRules"
    ref="spuFormRef"
    label-width="100px"
  >
    <el-form-item label="SPU名称" prop="spuName">
      <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
        <el-option
          v-for="trademark in trademarkList"
          :label="trademark.tmName"
          :value="trademark.id"
          :key="trademark.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input
        type="textarea"
        :rows="3"
        v-model="spuInfo.description"
      ></el-input>
    </el-form-item>

    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload
        v-model:file-list="spuInfo.spuImageList"
        :action="`${BASE_URL}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select
        v-model="spuInfo.spuSaleAttr"
        :placeholder="`还剩下${filterBaseSaleAttrList.length}个未选择`"
      >
        <el-option
          v-for="baseSaleAttr in filterBaseSaleAttrList"
          :label="baseSaleAttr.name"
          :value="baseSaleAttr.name"
          :key="baseSaleAttr.id"
        />
      </el-select>
      <el-button
        type="primary"
        :disabled="!spuInfo.spuSaleAttr"
        @click="addSpuSaleAttr"
        >添加销售属性</el-button
      >

      <el-table border :data="spuInfo.spuSaleAttrList">
        <el-table-column
          label="序号"
          width="80px"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性名"
          prop="saleAttrName"
          width="120px"
        ></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row, $index }">
            <el-tag
              v-for="tag in row.spuSaleAttrValueList"
              :key="tag"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="handleClose(row, tag)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput(row)"
            >
              + New
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template v-slot="{ row, $index }">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="真的确定要删除此条数据么?"
              @confirm="deleteAttr($index)"
            >
              <template #reference>
                <el-button
                  title="删除"
                  type="danger"
                  size="small"
                  :icon="Delete"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="spuSubmitSpuForm(spuFormRef)"
        >保存</el-button
      >
      <el-button @click="delSpuInfo">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SpuForm",
}
</script>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed, nextTick } from "vue"
import type {
  UploadProps,
  UploadFiles,
  UploadFile,
  FormInstance,
  FormRules,
} from "element-plus"
import { Plus, Delete, InfoFilled } from "@element-plus/icons-vue"
import { ElMessage, ElInput } from "element-plus"
import {
  reqGetAllTrademarkList,
  reqGetBaseSaleAttrList,
  reqSaveSpuInfo,
  reqGetSpuImageList,
  reqGetSpuSaleAttrList,
  reqUpdateSpuInfo,
} from "@/api/product/spu"
import { useCategoryListStore } from "@/stores/categoryList"
const categoryStore = useCategoryListStore()
const emits = defineEmits(["changeScene"])
const props = defineProps(["currentSpuInfo"])
const dialogImageUrl = ref("")
const dialogVisible = ref(false)
// const fileList = ref<UploadUserFile[]>([])

// 获取trademarkList和销售属性存值
const trademarkList = ref([])
const baseSaleAttrList = ref([])

// 定义一个存储spu相关数据的变量
const spuInfo = reactive({
  spuName: "",
  tmId: "", // spu品牌
  description: "", // spu描述
  spuImageList: [], // 存储spu图片的数组
  spuSaleAttrList: [], // 基本销售属性
  spuSaleAttr: "", // 收集选中的属性
  category3Id: "", // 三级id
  ...props.currentSpuInfo,
})

// 数据校验
const formSize = ref("default")
const spuFormRef = ref<FormInstance>()
// 添加校验规则
const spuRules = reactive<FormRules>({
  spuName: [
    { required: true, message: "请输入SPU名称", trigger: "blur" },
    { min: 1, max: 10, message: "SPU名称在1-10个字符之间", trigger: "blur" },
  ],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [
    {
      required: true,
      message: "请选择一张图片",
      type: "array",
      trigger: "change",
    },
  ],
  spuSaleAttrList: [
    {
      required: true,
      message: "请至少添加一个属性",
      type: "array",
      trigger: "click",
    },
  ],
})

// 动态读取环境变量中的值
const BASE_URL = import.meta.env.VITE_API_URL

// 添加或是删除基础销售属性值相关的变量
const inputValue = ref("")
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 获取trademarkList和销售属性
onMounted(async () => {
  try {
    const { id } = spuInfo
    // 原来的两个函数
    let promises = [reqGetAllTrademarkList(), reqGetBaseSaleAttrList()]
    if (id) {
      // 如果id有值，说明此时是编辑操作，需要再加上两个接口函数
      promises = promises.concat([
        reqGetSpuImageList(id),
        reqGetSpuSaleAttrList(id),
      ])
    }
    const [
      responseTrademarkList,
      responseBaseSaleAttrList,
      responseSpuImageList,
      responseSpuSaleAttrList,
    ] = await Promise.all(promises)
    // console.log(responseTrademarkList, responseBaseSaleAttrList,responseSpuImageList, responseSpuSaleAttrList)
    trademarkList.value = responseTrademarkList
    baseSaleAttrList.value = responseBaseSaleAttrList
    if (responseSpuImageList && responseSpuSaleAttrList) {
      spuInfo.spuImageList = responseSpuImageList.map((item) => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl,
        }
      })

      spuInfo.spuSaleAttrList = responseSpuSaleAttrList
    }
  } catch (error) {
    ElMessage.error("获取属性失败...")
  }
})

// 缩略图上传相关的事件处理程序
// 删除图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  // uploadFile 被删除的图片
  // uploadFiles 剩余的图片数据
  spuInfo.spuImageList = uploadFiles
}
// 预览图片
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 图片上传
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response: any, // 服务器端响应回来的结果,里面的data属性包含图片在服务器端的地址
  uploadFile: UploadFile, // 是经过改造的响应对象,不但包含图片在服务器响应回来的结果,还包含图片本身的信息
  uploadFiles: UploadFiles // 相当于是上传的所有图片的数组
) => {
  // console.log(response, uploadFile,UploadFile)
  // spuInfo.spuImageList.push({
  //   imgName: uploadFile.name,
  //   imgUrl: response.data,
  // })
  spuInfo.spuImageList = uploadFiles
  // 清空校验规则
  spuFormRef.value!.clearValidate(["spuImageList"])
}
// 图片校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("上传图片的格式只能是jepg!")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M,请重新选择!")
    return false
  }
  return true
}

// 添加销售属性
const addSpuSaleAttr = () => {
  const spuSaleAttrList = spuInfo.spuSaleAttrList
  if (
    spuSaleAttrList.length &&
    spuSaleAttrList.some((item) => item.spuSaleAttrValueList.length == 0)
  ) {
    ElMessage.error("有属性值为空，请添加...")
    return // 不要添加了
  }
  const id = baseSaleAttrList.value.find(
    (item) => item.name == spuInfo.spuSaleAttr
  ).id
  spuInfo.spuSaleAttrList.push({
    baseSaleAttrId: id,
    inputVisible: false,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],
  })
  spuInfo.spuSaleAttr = "" // 清空下拉框选项
  // 清空输入框的值
  spuInfo.spuSaleAttr = ""
  // 清空校验规则
  spuFormRef.value!.clearValidate(["spuSaleAttrList"])
}

// 使用计算属性处理销售属性展示
const filterBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseSale) => {
    return !spuInfo.spuSaleAttrList.find(
      (item) => baseSale.name === item.saleAttrName
    )
  })
})
// 清除当前属性
const deleteAttr = (index: number) => {
  spuInfo.spuSaleAttrList.splice(index, 1)
}

// 销售属性值相关方法
const handleClose = (row, tag) => {
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1)
}

const showInput = (row) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = (row) => {
  if (inputValue.value) {
    if (
      row.spuSaleAttrValueList.find(
        (item) => item.saleAttrValueName === inputValue.value
      )
    ) {
      ElMessage.error("属性值不能重复,请更换一个...")
      // inputVisible.value = false
      row.inputVisible = false
      inputValue.value = ""
      return // 不再向下执行
    }
    const id = baseSaleAttrList.value.find(
      (item) => item.name === row.saleAttrName
    ).id
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: id,
      saleAttrValueName: inputValue.value,
      saleAttrName: row.saleAttrName,
    })
  }
  row.inputVisible = false
  inputValue.value = ""
}

// 提交前的校验
const spuSubmitSpuForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 对要添加的销售属性值再做判断
      const spuSaleAttrList = spuInfo.spuSaleAttrList
      if (
        spuSaleAttrList.length &&
        !spuSaleAttrList.every((item) => item.spuSaleAttrValueList.length)
      ) {
        ElMessage.error("有属性值为空，请添加...")
        return // 不要添加了
      }
      // 提取一下图片的内容
      // spuInfo.spuImageList = spuInfo.spuImageList.map((item) => {
      //   return {
      //     imgName: item.name,
      //     imgUrl: item.response.data,
      //   }
      // })
      // 获取存储3Id
      spuInfo.category3Id = categoryStore.category3Id
      if (spuInfo.id) {
        // 此时是更新操作
        await reqUpdateSpuInfo(spuInfo)
      } else {
        // 才是真正的添加spuInfo
        await reqSaveSpuInfo(spuInfo)
      }
      ElMessage.success("操作Spu成功")
      emits("changeScene", 1)
    } else {
      ElMessage.error("提交失败")
    }
  })
}
const delSpuInfo = () => {
  emits("changeScene", 1)
}
</script>

<style scoped></style>
